package utils

import (
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/sirupsen/logrus"
)

var daysMatcher = regexp.MustCompile(`(\d+)d`)

func ParseDuration(duration string) (time.Duration, error) {
	var days string
	var matched = daysMatcher.FindAllStringSubmatch(duration, -1)
	if len(matched) > 0 {
		days = matched[0][1]
	}
	var replaced = daysMatcher.ReplaceAllString(strings.ReplaceAll(duration, "-", ""), "")
	var td time.Duration
	if replaced != "" {
		var err error
		td, err = time.ParseDuration(replaced)
		if err != nil {
			return td, err
		}
	}
	iDays, _ := strconv.Atoi(days)
	td += time.Duration(iDays*24) * time.Hour

	return td, nil
}

func GetTimeFromDuration(fromDuration string, inteval int64, tailMode bool) time.Time {
	var now = time.Now()
	if fromDuration != "" {
		from, err := ParseDuration(fromDuration)
		if err != nil {
			logrus.Errorf("From设置（%s）错误，%s,重新使用默认配置", fromDuration, err)
		} else {
			return now.Add(-1 * from)
		}
	}

	if tailMode {
		return now.Add(time.Duration(-inteval))
	} else {
		//report mode
		return now.Add(-7 * 24 * time.Hour)
	}
}
